package com.mbinno.android.comm.utils;

import android.annotation.SuppressLint;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SystemPropertiesUtil {
    private final static String CLASS_NAME = "android.os.SystemProperties";


    @SuppressLint("PrivateApi")
    public static String getProperty(String key, String defaultValue) {
        String value = defaultValue;

        try {
            Class<?> c = Class.forName(CLASS_NAME);
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) get.invoke(c, key, defaultValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;

    }


    public static String getPropByShell(String propName) {
        String result = "";
        try {
            // 执行 shell 命令 "getprop"
            Process process = Runtime.getRuntime().exec("getprop " + propName);

            // 读取命令的输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                StringBuilder output = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }

                // 关闭流
                result = output.toString().trim();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    public static Map<String ,Integer> getAllPropertyMap(){
        Map<String ,Integer> maps = new HashMap<>();
        try {
            List<String> propertyList = getAllPropertyList();
            for (String property : propertyList){
                maps.put(property,1);
            }

        } catch (IOException e) {e.printStackTrace();}

        return  maps;
    }

    private static List<String> getAllPropertyList() throws IOException {
        List<String> propList = new ArrayList<>();
        Process process = Runtime.getRuntime().exec("getprop");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                propList.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return propList;
    }


}
